from app import db
from datetime import datetime

class OperationLog(db.Model):
    """操作日志模型"""
    __tablename__ = 'operation_logs'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), comment='用户ID（可为空，表示系统操作）')
    admin_id = db.Column(db.Integer, db.ForeignKey('admins.id'), comment='管理员ID')
    action = db.Column(db.String(100), nullable=False, comment='操作类型')
    resource_type = db.Column(db.String(50), comment='资源类型')
    resource_id = db.Column(db.Integer, comment='资源ID')
    description = db.Column(db.Text, comment='操作描述')
    ip_address = db.Column(db.String(45), comment='IP地址')
    user_agent = db.Column(db.Text, comment='用户代理')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f'<OperationLog {self.action}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'admin_id': self.admin_id,
            'action': self.action,
            'resource_type': self.resource_type,
            'resource_id': self.resource_id,
            'description': self.description,
            'ip_address': self.ip_address,
            'user_agent': self.user_agent,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
    
    @classmethod
    def log_operation(cls, action, description=None, user_id=None, admin_id=None, 
                     resource_type=None, resource_id=None, ip_address=None, user_agent=None):
        """记录操作日志"""
        log = cls(
            action=action,
            description=description,
            user_id=user_id,
            admin_id=admin_id,
            resource_type=resource_type,
            resource_id=resource_id,
            ip_address=ip_address,
            user_agent=user_agent
        )
        
        db.session.add(log)
        db.session.commit()
        
        return log 